<?php
declare (strict_types=1);

namespace app\common\queue\bokecc;

use app\common\library\Queue;
use app\course\logic\live\admin\LiveSectionSyncLogs;
use app\course\logic\live\BokeZB;
use app\course\model\live\admin\CourseSectionLive;
use think\facade\Env;
use think\facade\Request;

/**
 * Class SyncLiveViewRecord
 *
 * @package app\course\jobs\live
 */
class YZBViewRecord
{
    public function run()
    {
        $data = Request::post();
        // 直播ID
        $liveId = $data['live_id'];
        // 直播间ID
        $roomId = $data['room_id'];
        // 记录
        $logObj = new LiveSectionSyncLogs();
        // 是否同步过记录
        $isSynced = $logObj->isSynced($roomId, $liveId);
        if ($isSynced) return;
        // 累计需要同步的数量
        $totalCount = $data['total_count'] ?? 0;
        // 单次同步的数量
        $pageNum = 200;
        // 当前同步的页码
        $pageIndex = $data['page'] ?? 1;
        // 累计同步成功数量
        $successCount = $data['success_count'] ?? 0;
        // 课程ID
        $courseId = $data['course_id'] ?? 0;
        // 课程ID
        $courseSectionId = $data['course_section_id'] ?? 0;
        if (!$courseId || !$courseSectionId) {
            // 根据直播间ID获取
            $section         = (new CourseSectionLive)->where('cc_room_id', $roomId)->field(['room_no', 'course_id'])->findOrEmpty();
            $courseSectionId = $section->getAttr('room_no');
            $courseId        = $section->getAttr('course_id');
            if (!$courseId || !$courseSectionId) return;
        }
        // 调用接口获取
        $response = $this->getStatis($liveId, $pageNum, $pageIndex);
        // 总记录数量
        $pageCount = $response->count;
        if (Env::get('app_debug')) {
            echo '第【' . $pageIndex . '】次同步直播间【' . $roomId . '】,直播ID为【' . $liveId . '】的观看时，共计【' . $pageCount . '】条数据';
        }
        if ($pageCount > 0) {
            // 更新记录,覆盖累计观看时长
            $count = $this->updatedOrCreated($courseId, $courseSectionId, $response->liveViewerStatisConclusions);
            // 继续推送任务，按分页数据同步
            Queue::push('SyncLiveViewRecord', [
                'live_id'       => $liveId,
                'room_id'       => $roomId,
                'page'          => $pageIndex + 1,
                'total_count'   => $totalCount + $pageCount,
                'success_count' => $successCount + $count
            ], 5);
        } else {
            $log = [
                'room_id'           => $roomId,
                'live_id'           => $liveId,
                'total_count'       => $totalCount,
                'success_count'     => $successCount,
                'course_id'         => $courseId,
                'course_section_id' => $courseSectionId
            ];
            // 更新同步记录数
            $logObj->updateOrCreatedLog($log);
        }
    }

    protected function getStatis($liveId, $pageNum, $pageIndex)
    {
        $cc = new BokeZB();
        return $cc->statis($liveId, $pageNum, $pageIndex);
    }

    /**
     * 创建直播观看记录
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/11/11
     *
     * @static
     * @param int   $courseId
     * @param int   $courseSectionId
     * @param array $liveViewerStatisConclusions
     * @return int
     */
    protected function updatedOrCreated(int $courseId, int $courseSectionId, array $liveViewerStatisConclusions): int
    {
        $count = 0;
        foreach ($liveViewerStatisConclusions as $liveViewerStatisConclusion) {
            // 观看直播时长
            $watchTime = $liveViewerStatisConclusion->watchTime;
            $userId    = $liveViewerStatisConclusion->viewerId;
            // 是否为本地系统用户ID
            if (is_numeric($userId)) {
                // 推送学习记录处理任务队列
                Queue::push('LearnRecord', [
                    'course_id'  => $courseId,
                    'section_id' => $courseSectionId,
                    'mid'        => $userId,
                    'watch_time' => $watchTime
                ]);
                $count++;
            }
        }

        return $count;
    }
}